package com.recipedb.sprint.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.recipedb.sprint.entity.Sessions;
import com.recipedb.sprint.entity.Users;
import com.recipedb.sprint.service.LlmSessionService;
import com.recipedb.sprint.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.Map;
import java.util.List;
import java.util.HashMap;

/**
 * LLM 会话控制层
 */
@RestController
@RequestMapping("/api/llm/session")
public class LlmSessionController {

    @Autowired
    private UsersService usersService;

    @Autowired
    private LlmSessionService llmSessionService;

    /**
     * 创建新会话并调用大模型
     */
    @PostMapping
    public ResponseEntity<Map<String, Object>> createSessionAndRunLlm(@RequestBody Map<String, Object> request) throws JsonProcessingException {
        Long userid = Long.valueOf(request.get("userid").toString());
        String userInput = (String) request.get("userInput");
        String model = (String) request.get("model");
        boolean useSystemPrompt = request.get("useSystemPrompt") != null && (Boolean) request.get("useSystemPrompt");

        // preferences 是前端传过来的 JSON 对象
        Object preferencesObj = request.get("preferences");
        String preferencesJson = new ObjectMapper().writeValueAsString(preferencesObj);

        Map<String, Object> result = llmSessionService.createSessionAndRunLlm(
                userid,
                userInput,
                model,
                useSystemPrompt,
                preferencesJson
        );

        // 创建返回的 Map
        Map<String, Object> response = new HashMap<>();
        response.put("sessionId", result.get("sessionId"));
        response.put("redisKey", result.get("redisKey"));
        response.put("status", "success");
        response.put("message", "会话创建成功");

        return ResponseEntity.ok(response);
    }

    /**
     * 查询单个会话详情
     */
    @GetMapping("/{sessionId}")
    public ResponseEntity<Sessions> getSessionById(@PathVariable Long sessionId) {
        Sessions session = llmSessionService.getSessionById(sessionId);
        return ResponseEntity.ok(session);
    }

    /**
     * SSE 流式输出接口 - 基于 Redis key
     */
    @GetMapping("/stream/{redisKey}")
    public SseEmitter streamSession(@PathVariable String redisKey) {
        SseEmitter emitter = new SseEmitter(0L); // 0 = 不超时
        llmSessionService.streamSessionByRedisKey(redisKey, emitter);
        return emitter;
    }

    @GetMapping("/my")
    public ResponseEntity<List<Sessions>> getUserOwnSessions(
            @RequestHeader("Authorization") String token) {
        // 1. 从Token中解析当前登录用户的ID
        String pureToken = token.startsWith("Bearer ") ? token.substring(7) : token;
        Users user = usersService.getUserByToken(pureToken);
        Long userId = user.getUserid();

        // 2. 调用Service查询该用户的所有会话
        List<Sessions> sessions = llmSessionService.getUserOwnSessions(userId);

        // 3. 返回结果
        return ResponseEntity.ok(sessions);
    }


    /**
     * 用户为会话提交反馈（评分+文字反馈）
     * 接口路径：/api/llm/session/{sessionId}/feedback
     */
    @PutMapping("/{sessionId}/feedback")
    public ResponseEntity<Map<String, Object>> submitFeedback(
            @RequestHeader("Authorization") String token,
            @PathVariable Long sessionId,
            @RequestBody Map<String, Object> feedbackData) {
        try {
            // 1. 解析当前登录用户（权限校验）
            String pureToken = token.startsWith("Bearer ") ? token.substring(7) : token;
            Users currentUser = usersService.getUserByToken(pureToken);
            Long userId = currentUser.getUserid();

            // 2. 提取反馈数据（rating可为空，feedback可为空）
            Integer rating = feedbackData.get("rating") != null
                    ? Integer.valueOf(feedbackData.get("rating").toString())
                    : null;
            String feedback = (String) feedbackData.get("feedback"); // 允许为null或空字符串

            // 3. 调用服务层提交反馈
            llmSessionService.submitFeedback(sessionId, userId, rating, feedback);

            // 4. 返回成功响应
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("msg", "反馈提交成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            // 异常处理（包含权限不足、参数无效等情况）
            Map<String, Object> error = new HashMap<>();
            error.put("code", 500);
            error.put("msg", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }


}
